package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.model.po.CourseCategory;
import com.xuecheng.content.service.CourseCategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 课程分类查询业务接口实现类
 */
@Service
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory> implements CourseCategoryService {

    @Autowired
    private CourseCategoryMapper courseCategoryMapper;

    /**
     * 查询课程分类
     *
     * @param id 根节点id
     * @return
     */
    public List<CourseCategoryTreeDto> queryTreeNodes(String id) {
        // 条件构造器
        LambdaQueryWrapper<CourseCategory> queryWrapper = new LambdaQueryWrapper<>();
        // 设置条件
        queryWrapper.eq(CourseCategory::getParentid, id);
        // 查询数据库
        List<CourseCategory> courseCategories = courseCategoryMapper.selectList(queryWrapper);
        // 递归处理课程分类列表，并返回
        return courseCategories.stream().map(this::buildCourseCategoryTree).collect(Collectors.toList());
    }

    // 递归代码
    private CourseCategoryTreeDto buildCourseCategoryTree(CourseCategory category) {
        // 构建返回对象
        CourseCategoryTreeDto dto = new CourseCategoryTreeDto();

        // 对象拷贝
        BeanUtils.copyProperties(category, dto);

        // 查询数据库
        List<CourseCategory> children = courseCategoryMapper.selectList(
                new LambdaQueryWrapper<CourseCategory>()
                        .eq(CourseCategory::getParentid, category.getId()));

        if (!children.isEmpty()) {
            dto.setChildrenTreeNodes(children.stream().map(this::buildCourseCategoryTree).collect(Collectors.toList()));
        }

        return dto;

    }
}
